<template>
    <div class="ability-radar-page">
        <!-- 页面头部 -->
        <van-nav-bar title="能力雷达图" left-text="返回" left-arrow @click-left="handleBack">
            <template #right>
                <van-icon name="share-o" @click="shareAbilities" />
            </template>
        </van-nav-bar>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-section">
            <van-loading size="24px" vertical>加载中...</van-loading>
        </div>

        <!-- 内容区域 -->
        <div v-else class="content">
            <!-- 雷达图区域 -->
            <div class="radar-section">
                <div class="radar-container">
                    <RadarChart :data="radarData" />
                </div>
                <div class="radar-legend">
                    <div class="legend-item current">
                        <div class="legend-color"></div>
                        <span>当前能力</span>
                    </div>
                    <div v-if="showComparison" class="legend-item baseline">
                        <div class="legend-color"></div>
                        <span>基线能力</span>
                    </div>
                </div>
            </div>

            <!-- 能力详情列表 -->
            <div class="abilities-list">
                <div class="list-header">
                    <h3>能力详情</h3>
                    <van-button size="small" type="primary" plain @click="toggleComparison">
                        {{ showComparison ? '隐藏对比' : '显示对比' }}
                    </van-button>
                </div>

                <div class="ability-items">
                    <div v-for="ability in abilities" :key="ability.ability_type" class="ability-item"
                        @click="showAbilityDetail(ability)">
                        <div class="ability-info">
                            <div class="ability-header">
                                <span class="ability-name">{{ ability.ability_name }}</span>
                                <div class="ability-scores">
                                    <span class="current-score">{{ ability.current_level }}</span>
                                    <span v-if="showComparison && baselineAbilities[ability.ability_type!]"
                                        class="baseline-score">
                                        / {{ baselineAbilities[ability.ability_type!] }}
                                    </span>
                                </div>
                            </div>

                            <div class="progress-container">
                                <van-progress :percentage="(ability.current_level / 10) * 100" stroke-width="6"
                                    :color="getProgressColor(ability.current_level)" track-color="#f5f5f5" />
                                <div v-if="showComparison && baselineAbilities[ability.ability_type!]"
                                    class="baseline-progress">
                                    <van-progress
                                        :percentage="((baselineAbilities[ability.ability_type!] || 0) / 10) * 100"
                                        stroke-width="2" color="#ddd" track-color="transparent" />
                                </div>
                            </div>

                            <div class="ability-change">
                                <span v-if="getAbilityChange(ability)" :class="getChangeClass(ability)">
                                    {{ getAbilityChangeText(ability) }}
                                </span>
                            </div>
                        </div>

                        <van-icon name="arrow" color="#c8c9cc" />
                    </div>
                </div>
            </div>

            <!-- 历史趋势 -->
            <div class="history-section">
                <div class="section-header">
                    <h3>能力趋势</h3>
                    <van-button size="small" type="default" plain @click="viewFullHistory">
                        查看详情
                    </van-button>
                </div>

                <div class="trend-chart">
                    <!-- 这里可以添加折线图显示能力变化趋势 -->
                    <div class="trend-placeholder">
                        <van-icon name="chart-trending-o" size="48" color="#ddd" />
                        <p>能力趋势图</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- 能力详情弹窗 -->
        <van-popup v-model:show="showDetailPopup" position="bottom" :style="{ height: '70%' }" round closeable>
            <DimensionDetail v-if="selectedAbility" :ability="selectedAbility" @close="showDetailPopup = false" />
        </van-popup>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { userApi, type UserAbility } from '@/api'
import { useUserStore } from '@/stores/user'
import RadarChart from '@/components/RadarChart.vue'
import DimensionDetail from '@/components/DimensionDetail.vue'

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const loading = ref(true)
const abilities = ref<UserAbility[]>([])
const baselineAbilities = ref<Record<string, number>>({})
const showComparison = ref(false)
const showDetailPopup = ref(false)
const selectedAbility = ref<UserAbility | null>(null)

// 计算属性
const radarData = computed(() => {
    const datasets = [{
        label: '当前能力',
        data: abilities.value.map(ability => ability.current_level),
        backgroundColor: 'rgba(25, 137, 250, 0.2)',
        borderColor: '#1989fa',
        borderWidth: 2,
        pointBackgroundColor: '#1989fa',
        pointBorderColor: '#fff',
        pointBorderWidth: 2
    }]

    if (showComparison.value) {
        datasets.push({
            label: '基线能力',
            data: abilities.value.map(ability =>
                baselineAbilities.value[ability.ability_type!] || 0
            ),
            backgroundColor: 'rgba(221, 221, 221, 0.2)',
            borderColor: '#ddd',
            borderWidth: 2,
            pointBackgroundColor: '#ddd',
            pointBorderColor: '#fff',
            pointBorderWidth: 2
        })
    }

    return {
        labels: abilities.value.map(ability => ability.ability_name),
        datasets
    }
})

// 方法
const loadAbilities = async () => {
    try {
        loading.value = true
        const response = await userApi.getUserAbilities(userStore.userInfo!.id)
        const abilityData = response.data

        // 转换数据格式以匹配前端期望的结构
        const currentAbilities = abilityData.current_abilities
        abilities.value = [
            {
                ability_type: 'breaking_ice',
                ability_name: 'Breaking Ice',
                current_level: currentAbilities.breaking_ice
            },
            {
                ability_type: 'empathy',
                ability_name: 'Empathy',
                current_level: currentAbilities.empathy
            },
            {
                ability_type: 'conversation_flow',
                ability_name: 'Conversation Flow',
                current_level: currentAbilities.conversation_flow
            }
        ]

        // 模拟基线数据（实际应该从API获取）
        baselineAbilities.value = abilities.value.reduce((acc, ability) => {
            acc[ability.ability_type!] = Math.max(1, ability.current_level - Math.floor(Math.random() * 20))
            return acc
        }, {} as Record<string, number>)
    } catch (error) {
        console.error('加载能力数据失败:', error)
        showToast('加载数据失败，请重试')
    } finally {
        loading.value = false
    }
}

const getProgressColor = (level: number) => {
    if (level >= 8) return '#07c160'
    if (level >= 6) return '#ffd21e'
    if (level >= 4) return '#ff976a'
    return '#ee0a24'
}

const getAbilityChange = (ability: UserAbility) => {
    const baseline = baselineAbilities.value[ability.ability_type!]
    if (!baseline) return 0
    return ability.current_level - baseline
}

const getChangeClass = (ability: UserAbility) => {
    const change = getAbilityChange(ability)
    if (change > 0) return 'positive-change'
    if (change < 0) return 'negative-change'
    return 'no-change'
}

const getAbilityChangeText = (ability: UserAbility) => {
    const change = getAbilityChange(ability)
    if (change > 0) return `+${change}`
    if (change < 0) return `${change}`
    return '无变化'
}

const toggleComparison = () => {
    showComparison.value = !showComparison.value
}

const showAbilityDetail = (ability: UserAbility) => {
    selectedAbility.value = ability
    showDetailPopup.value = true
}

const viewFullHistory = () => {
    router.push('/abilities/history')
}

const shareAbilities = () => {
    showToast('分享功能')
}

const handleBack = () => {
    router.back()
}

// 生命周期
onMounted(() => {
    loadAbilities()
})
</script>

<style lang="scss" scoped>
.ability-radar-page {
    min-height: 100vh;
    background: #f7f8fa;

    .loading-section {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 300px;
    }

    .content {
        padding-bottom: 20px;
    }

    .radar-section {
        background: white;
        padding: 20px;
        margin-bottom: 12px;

        .radar-container {
            height: 300px;
            margin-bottom: 20px;
        }

        .radar-legend {
            display: flex;
            justify-content: center;
            gap: 24px;

            .legend-item {
                display: flex;
                align-items: center;
                gap: 8px;
                font-size: 14px;
                color: #646566;

                .legend-color {
                    width: 12px;
                    height: 12px;
                    border-radius: 2px;
                }

                &.current .legend-color {
                    background: #1989fa;
                }

                &.baseline .legend-color {
                    background: #ddd;
                }
            }
        }
    }

    .abilities-list {
        background: white;
        padding: 20px;
        margin-bottom: 12px;

        .list-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;

            h3 {
                font-size: 18px;
                color: #323233;
                margin: 0;
            }
        }

        .ability-items {
            .ability-item {
                display: flex;
                align-items: center;
                padding: 16px 0;
                border-bottom: 1px solid #f5f5f5;
                cursor: pointer;

                &:last-child {
                    border-bottom: none;
                }

                &:active {
                    background: #f7f8fa;
                }

                .ability-info {
                    flex: 1;

                    .ability-header {
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                        margin-bottom: 8px;

                        .ability-name {
                            font-size: 16px;
                            color: #323233;
                            font-weight: 500;
                        }

                        .ability-scores {
                            font-size: 16px;
                            font-weight: bold;

                            .current-score {
                                color: #1989fa;
                            }

                            .baseline-score {
                                color: #969799;
                            }
                        }
                    }

                    .progress-container {
                        position: relative;
                        margin-bottom: 8px;

                        .baseline-progress {
                            position: absolute;
                            top: 0;
                            left: 0;
                            right: 0;
                        }
                    }

                    .ability-change {
                        font-size: 12px;

                        .positive-change {
                            color: #07c160;
                        }

                        .negative-change {
                            color: #ee0a24;
                        }

                        .no-change {
                            color: #969799;
                        }
                    }
                }
            }
        }
    }

    .history-section {
        background: white;
        padding: 20px;

        .section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;

            h3 {
                font-size: 18px;
                color: #323233;
                margin: 0;
            }
        }

        .trend-chart {
            .trend-placeholder {
                text-align: center;
                padding: 40px 20px;
                color: #969799;

                p {
                    margin: 12px 0 0 0;
                    font-size: 14px;
                }
            }
        }
    }
}
</style>